package com.mvc.common;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.model.ActionView;
import com.mvc.util.MvcUtil;

/**
 * Servlet implementation class ActionServlet
 */
@WebServlet("*.go")
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = request.getServletPath();
		System.out.println("Action Servlet url: " + url);
		String methodName = url.substring(url.lastIndexOf("/")).split("\\.")[0].substring(1);
		HashMap<String,String> map = (HashMap<String,String>)request.getServletContext().getAttribute(MvcUtil.APPLITION_MVC_MAPPING);
		String className = map.get(url);
		System.out.println("Action Servlet url mapping class: " + className);
		
		try {
			Class<?> cls = Class.forName(className);
			Object obj = cls.newInstance();
			Method method = cls.getMethod(methodName, new Class[]{HttpServletRequest.class,HttpServletResponse.class});
			ActionView view = (ActionView)method.invoke(obj, new Object[]{request,response});
			fixAttribute(request, view);
			String path = view.getPath();
			RequestDispatcher rd = this.getServletContext().getRequestDispatcher(path);
			rd.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/error.jsp");
			rd.forward(request, response); 
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}
	
	private void fixAttribute(HttpServletRequest request, ActionView actionView){
		 HashMap<String,Object> map = actionView.getAttrMap();
//		 System.out.println(map);
		 Set keySet = map.keySet();
		 Iterator i = keySet.iterator();
		 while(i.hasNext()){
			 String key = (String)i.next();
			 Object obj = map.get(key);
			 request.setAttribute(key, obj);
		 }
	 }

}
